import { render, WeElement, define } from "omi"
import "./index.css"
import { post, toastSuccess } from '../../../utils/util.js'

let is_newAddress = true;

define('index', class extends WeElement {
  // config = {
  //   navigationBarTitleText: "收货地址"
  // }

  data = {
    arrows_right: "",
    set_default: true,//默认地址设置
    area_select: false,
    area_code: '86',//选择的区号
    temp_code: '86',
    area_code_item: [
      { type: '中国大陆+86', code:86, checked: 'true' },
      { type: '香港+852', code: 852 },
      { type: '澳门+853', code: 853 },
      { type: '台湾+886', code: 886 },
    ],
    region_default: ['广东省', '广州市', '海珠区'],//地区picker默认值
    region: "",//所在地区
    consignee_inp: "",//收货人
    phone_num: "",//电话号码
    detailed_address: "",//详细地址
    address_id: ""//地址id编辑地址时需要返回给后台，新地址不用
  }

  install(options){
    console.log("options");
    console.log(options);
    if(options.data){
      is_newAddress = false;
      console.log("编辑收货地址")
      let result = JSON.parse(options.data);
      console.log(result);
      // console.log(result.area_info);
      wx.setNavigationBarTitle({
        title: '编辑收货地址'
      })
      //自动获取填入之前的地址信息
      this.data.consignee_inp = result.name;
      this.data.phone_num = result.phone;
      this.data.region = result.area_info.split(' ');
      this.data.detailed_address = result.address_detail;
      this.data.set_default = result.checked;
      this.data.address_id = result.address_id;
      // console.log(this.data.region)
      this.update();
    }else{
      is_newAddress = true;
      console.log("新建");
      wx.setNavigationBarTitle({
        title: '添加新地址'
      })
      //清空内容
      this.data.consignee_inp = '';
      this.data.phone_num = '';
      this.data.region = '';
      this.data.detailed_address = '';
      this.data.set_default = false;
      this.data.address_id = '';
      this.update();
    }
    
    this.data.arrows_right = require('../../../images/arrows-right.png');
    this.update();
  }
// 设置默认地址
  setDefault=(e)=>{
    console.log(e)
    this.data.set_default = e.detail.value;
    console.log(this.data.set_default)
    this.update();
  }

//打开区号选择
  areaCodeSelect=()=>{
    this.data.area_select = true;
    this.update();
  }
// 隐藏遮罩层
  hindWrap = () => {
    this.data.area_select = false;//隐藏区号选择层
    this.update();
  }
//区号选择结果
  areaCodeRadio=(e)=>{
    console.log(e)
    this.data.temp_code = e.detail.value;
  }
//防止冒泡
  cancelBubble=()=>{
    //只允许一个遮罩层存在
    this.data.area_select = true
    this.update();
  }
//取消选择区号
  cancelSelect=()=>{
    this.data.area_select = false;
    this.update();
  }
//确定选择区号
  confirmSelect=()=>{
    this.data.area_select = false;
    this.data.area_code = this.data.temp_code;
    this.update();
  }

//地区选择
  bindRegionChange=(e)=>{
    console.log(e.detail.value)
    // this.data.region = e.detail.value[0] + e.detail.value[1] + e.detail.value[2];
    this.data.region = e.detail.value;
    this.update();
    console.log(this.data.region)
  }

//获取收货人
  getConsignee=(e)=>{
    this.data.consignee_inp = e.detail.value;
    console.log(e.detail.value)
  }
//获取电话号码
  getPhoneNum=(e)=>{
    this.data.phone_num = e.detail.value;
  }
  //获取详细地址
  getDetailedAddress=(e)=>{
    this.data.detailed_address = e.detail.value;
  }
//添加新地址保存
  save=()=>{
    const regExp = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;

    if(!this.data.consignee_inp){
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
    }else if (!regExp.test(this.data.phone_num)){
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
    }else if (!this.data.region){
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      })
    }else if(!this.data.detailed_address){
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
    }else{
      // wx.navigateTo({
      //   url: '../my_shipping_address/index',
      // })
     
      if (is_newAddress){
        console.log('即将新建收货地址')
        //添加请求
        post('https://yaochiwanback.bluej.cn/api/refund/add_address', {
          address_realname: this.data.consignee_inp,//收货人
          address_mob_phone: this.data.phone_num,//电话
          province: this.data.region[0],//省
          city: this.data.region[1],//市
          area: this.data.region[2],//地区
          address_details: this.data.detailed_address,//详细地址
          address_is_default: this.data.set_default ? 1 : 0//是否默认地址
        }).then((res) => {
          console.log(res)
          toastSuccess('添加成功');
          wx.navigateBack({
            delta: 1
          })
        })
      }else{
        console.log('这是编辑旧的地址')
        //修改请求
        post('https://yaochiwanback.bluej.cn/api/refund/change_address',{
          address_id: this.data.address_id,//地址id
          address_realname: this.data.consignee_inp,//收货人
          address_mob_phone: this.data.phone_num,//电话
          province: this.data.region[0],//省
          city: this.data.region[1],//市
          area: this.data.region[2],//地区
          address_details: this.data.detailed_address,//详细地址
          address_is_default: this.data.set_default ? 1 : 0//是否默认地址
        }).then((res)=>{
          console.log(res)
          toastSuccess('修改成功');
          wx.navigateBack({
            delta: 1
          })
        })
      }
      console.log(this.data.address_id)
      console.log(this.data.consignee_inp)
      console.log(this.data.phone_num)
      console.log(this.data.area_code)
      console.log(this.data.region)
      // console.log(this.data.region[0], this.data.region[1], this.data.region[2])
      console.log(this.data.detailed_address)
      console.log(this.data.set_default)
    }
   
  }

  render() {

    let { arrows_right, region_select, area_code_item, hot_cities, provinces} = this.data;

    return (
      <view class='add_shipping_address'>
        <view class='consignee flex'>
          <label>收货人</label>
          <input type='text' value={consignee_inp} class='consignee_inp' maxlength='20' bindinput={getConsignee}/>
        </view>
        <view class='phone flex'>
          <label>电话号码</label>
          <input type='number' value={phone_num} class='phone_num' maxlength='11' bindinput={getPhoneNum}/>
          <label class='phone_area_code' bindtap={areaCodeSelect}>+{area_code}<image class='select_btn' src={arrows_right} mode='widthFix'></image></label>
        </view>
        <view class='region flex'>
          <label>所在地区</label>
          <input type='text' class='region_inp' maxlength='30' value={region} disabled="true"/>
          <picker
            mode="region"
            bindchange={bindRegionChange}
            value={region_default}
          >
            <view class="picker">
              <image class='select_btn' src={arrows_right} mode='widthFix'></image>
          </view>
          </picker>
          
        </view>
        <view class='detailed_address flex flex2'>
          <label class='address_tips'>详细地址：如道路、门牌号、小区、楼栋号、单元室等</label>
          <textarea type='text' value={detailed_address} class='detailed_address_inp' maxlength='30' bindinput={getDetailedAddress}/>
        </view>
        <view class='set_default flex'>
          <label>设为默认地址</label>
            <switch 
            color="#ff4e00"
            checked={set_default}
            bindchange={setDefault}
            /> 
        </view>

        {
          area_select && 
          <view class='area_code_wrap' bindtap={hindWrap}>
            <view class='area_code_content' catchtap={cancelBubble}>
              <radio-group class='radio_group' bindchange={areaCodeRadio}>
                {
                  area_code_item.map((item, index) => (
                    <label class='radio' key={index}>
                      <text> {item.type} </text> 
                      <radio
                        color="#ff4e00"
                        icon="none"
                        value={item.code}/>
                    </label>
                  ))
                }    
              </radio-group>

              <view class='bottom_btn'>
                <button catchtap={cancelSelect}>取消</button>
                <button catchtap={confirmSelect}>确定</button>
              </view>
            </view>
          </view>
        }
        
        <view class='save'>
          <button bindtap={save}>保存</button>
        </view>
      </view>
    )
  }


})